package com.zdhr.igms.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zdhr.igms.demain.*;
import com.zdhr.igms.report.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;


@RequestMapping("/report")
@Controller
@CrossOrigin
public class ReportController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ReportService reportService;

    /**
     * 折现报表页面
     * @param id
     * @param holeName
     * @param segName
     * @param request
     * @return
     */
    @RequestMapping(value = "/graphPage")
    public String graphDataPage(Integer id,String holeName,String segName,HttpServletRequest request){
        request.setAttribute("id",id);
        request.setAttribute("holeName",holeName);
        request.setAttribute("segName",segName);
        return "igms/graphPage";
    }

    /**
     * 表格报表页面
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/reportPage")
    public String reportDataPage(Integer id, HttpServletRequest request){
        ReportData reportMap = new ReportData(id);
        List<ReportData> reportDataList = reportService.reportDataById(reportMap);
        ReportInfo reportInfoMap = new ReportInfo(id);
        ReportInfo reportInfo = reportService.reportInfoByInfo(reportInfoMap);
        request.setAttribute("reportDataList",reportDataList);
        request.setAttribute("reportInfo",reportInfo);
        Map map = new HashMap();
        switch (reportInfo.getContractNumber()){
            case 0:
                map.put("contractNumber","WDD/0266");
                break;
            case 1:
                map.put("contractNumber","WDD/0251");
                break;
            case 2:
                map.put("contractNumber","WDD/0215");
                break;
            case 3:
                map.put("contractNumber","WDD/0445");
                break;
            case 4:
                map.put("contractNumber","WDD/0193");
                break;
            case 5:
                map.put("contractNumber","WDD/0194");
                break;
            default:
                map.put("contractNumber","0");
        }
        switch (reportInfo.getContractor()){
            case 0:
                map.put("contractor","中国葛洲坝集团乌东德施工局");
                break;
            case 1:
                map.put("contractor","水电六局乌东德施工局");
                break;
            case 2:
                map.put("contractor","长江设计公司乌东德总承包项目部");
                break;
        }
        switch (reportInfo.getSupervisor()){
            case 0:
                map.put("supervisor","三峡发展乌东德监理部");
                break;
            case 1:
                map.put("supervisor","西北咨询公司乌东德监理中心");
                break;
        }
        switch (reportInfo.getUnitEngineeringName()){
            case 0:
                map.put("unitEngineeringName","大坝工程");
                break;
            case 1:
                map.put("unitEngineeringName","水垫塘及二道坝工程");
                break;
            case 2:
                map.put("unitEngineeringName","泄洪洞工程");
                break;
            case 3:
                map.put("unitEngineeringName","左岸引水发电系统工程");
                break;
            case 4:
                map.put("unitEngineeringName","右岸引水发电系统工程");
                break;
        }
        switch (reportInfo.getWay()){
            case 0:
                map.put("way","灌浆");
                break;
            case 1:
                map.put("way","单点压水");
                break;
            case 2:
                map.put("way","五点压水");
                break;
            case 3:
                map.put("way","简易压水");
                break;
            case 4:
                map.put("way","裂隙冲孔");
                break;
        }

        request.setAttribute("map",map);
        return "igms/reportPage";
    }

    /**
     * 通过id获取报表线性数据
     * @param id
     * @return
     */
    @PostMapping(value = "/queryReportLineData")
    @ResponseBody
    public String queryReportLineData(Integer id){
        ReportLineData reportMap = new ReportLineData(id);
        List<ReportLineData> reportLineData = reportService.reportLineDataById(reportMap);
        return JSON.toJSONString(reportLineData);
    }
    /**
     * 通过id获取报表数据
     * @param id
     * @return
     */
    @PostMapping(value = "/queryReportData")
    @ResponseBody
    public String queryReportData(Integer id){
        ReportData reportMap = new ReportData(id);
        System.out.println(reportMap);
        List<ReportData> reportData = reportService.reportDataById(reportMap);
        System.out.println(reportData);
        return JSON.toJSONString(reportData);
    }
    /**
     * 通过id获取报表信息数据
     * @param id
     * @return
     */
    @PostMapping(value = "/queryReportInfoByInfo")
    @ResponseBody
    public String queryReportInfoByInfo(Integer id){
        ReportInfo reportMap = new ReportInfo(id);
        System.out.println(reportMap);
        ReportInfo reportInfo = reportService.reportInfoByInfo(reportMap);
        System.out.println(reportInfo);
        return JSON.toJSONString(reportInfo);
    }
    /**
     * 通过id获取报表结果信息数据
     * @param id
     * @return
     */
    @PostMapping(value = "/reportStatisticsById")
    @ResponseBody
    public String reportStatisticsById(Integer id){
        ReportStatistics reportMap = new ReportStatistics(id);
        System.out.println(reportMap);
        ReportStatistics reportStatistics = reportService.reportStatisticsById(reportMap);
        System.out.println(reportStatistics);
        return JSON.toJSONString(reportStatistics);
    }

    /**
     * 文件上传
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(consumes = "multipart/form-data", value = "/upload", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String result = "";
        if (request.getContentLength() > 0) {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            try {
                inputStream = request.getInputStream();
                // 给新文件拼上时间毫秒，防止重名
                long now = System.currentTimeMillis();
                File file = new File("c:/", "file-" + now + ".txt");
                file.createNewFile();
                outputStream = new FileOutputStream(file);
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    outputStream.write(temp, 0, size);
                }
                logger.info("File load success.");
                result = "File load success.";
            } catch (IOException e) {
                logger.warn("File load fail.", e);
                result = "File load fail.";
            } finally {
                outputStream.close();
                inputStream.close();
            }
        }
        response.getWriter().write(result);
    }

    @PostMapping(value = "/readFile")
    @ResponseBody
    public String readFile() {
        StringBuffer data = new StringBuffer();
        try {
            String fileName = "D:\\G_HR1_001_20180413.JTF2";
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = null;
            while ((line = bufferedReader.readLine())!=null){
                data.append(line);
            }
            bufferedReader.close();
            fileReader.close();

            reportService.insertReport(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data.toString();
    }

    /**
     * 实时数据接口
     * @param data
     * @return
     */
    @PostMapping(value = "/realTimeDataAPI")
    @ResponseBody
    public String realTimeDataAPI(String data){
        if(null == data||"{}".equals(data)){
            //无数据
            return "501";
        }
        RealTimeData realTimeData = JSON.parseObject(data,RealTimeData.class);
        if(null != realTimeData){
            try {
                if(null!= realTimeData.getDate_time1()){
                    System.out.println(realTimeData);
                    reportService.insertRealTimeData(realTimeData);
                }
            }catch (Exception e){
                logger.error("实时数据持久化失败！",e);
                return "500";
            }
        }else{
            // 数据错误
            return "502";
        }
        return "200";
    }

}
